package com.example.pingze.handler;

import com.alibaba.fastjson.JSON;
import com.example.pingze.utils.WebUtils;
import com.example.pingze.vo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证过程中的异常处理
 *      统一异常返回格式
 *      将格式转换成json
 *      返回前端
 *
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //处理异常
        Result result = new Result("403","用户认证失败，请重新登录",null);
        String jsonString = JSON.toJSONString(result);
        WebUtils.renderString(response, jsonString);
    }
}
